package com.wangyang.service.Impl;

import com.wangyang.mapper.CategoryMapper;
import com.wangyang.pojo.Category;
import com.wangyang.pojo.Result;
import com.wangyang.service.CategoryService;
import com.wangyang.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result addCategory(Category category) {
        //从ThreadLocal中获取当前用户的id
        Integer uid = ThreadLocalUtil.get();
        categoryMapper.addCategory(uid, category.getCategoryName(), category.getCategoryAlias());
        return Result.success();
    }

    @Override
    public Result getAllCategory() {
        //从ThreadLocal中获取当前用户的id
        Integer uid = ThreadLocalUtil.get();
        List<Category> categoryList = categoryMapper.getCategoryByCreateuser(uid);
        return Result.success(categoryList);
    }

    @Override
    public Result getCategoryDetail(Integer id) {
        //从ThreadLocal中获取当前用户的id
        Integer uid = ThreadLocalUtil.get();
        //根据id查询分类信息
        Category category = categoryMapper.getCategoryById(id);
        //判断查询是否合法
        if(category==null || category.getCreateUser() != uid){ //分类不存在或分类不合法
            return Result.error("分类信息不存在或无权限访问改分类信息");
        }
        //正常返回
        return Result.success(category);
    }

    @Override
    public Result updateCategory(Category category) {
        //从ThreadLocal中获取当前用户的id
        Integer uid = ThreadLocalUtil.get();
        //根据id查询分类信息
        Category categoryq = categoryMapper.getCategoryById(category.getId());
        //判断查询是否合法
        if(categoryq==null || categoryq.getCreateUser() != uid){ //分类不存在或分类不合法
            return Result.error("分类信息不存在或无权限修改改分类信息");
        }
        categoryMapper.updateCategory(category);
        return Result.success();
    }

    @Override
    public Result deleteCategory(Integer id) {
        //从ThreadLocal中获取当前用户的id
        Integer uid = ThreadLocalUtil.get();
        //根据id查询分类信息
        Category categoryq = categoryMapper.getCategoryById(id);
        //判断查询是否合法
        if(categoryq==null || categoryq.getCreateUser() != uid){ //分类不存在或分类不合法
            return Result.error("分类信息不存在或无权限删除改分类信息");
        }
        categoryMapper.deleteCategoryById(id);
        return Result.success();
    }
}
